package com.ciaojian.client.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ciaojian.core.mapper.CouponPackageMapper;
import com.ciaojian.core.model.CouponPackage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 劵包表 服务实现类
 * </p>
 *
 * @author Atlakyn
 * @since 2021-03-03
 */
@Service
public class CouponPackageServiceImpl extends ServiceImpl<CouponPackageMapper, CouponPackage> {
    @Resource
    private CouponCodeServiceImpl couponCodeService;
    @Resource
    private CouponPackageMapper couponPackageMapper;

    /**
     * 获取卡包列表
     * <p>开始时间</p>
     * <p>卡包包含的卡券数量是否足够</p>
     */
    public List<CouponPackage> getCouponPackage(Integer displayMall) {

        QueryWrapper<CouponPackage> queryWrapper = new QueryWrapper<>();
        Date date = new Date();
        queryWrapper.le("start_time", date);
        queryWrapper.ge("end_time",date);
        if (displayMall!=null){
            queryWrapper.eq("display_mall",displayMall);
        }
        queryWrapper.eq("overdue",0);
        queryWrapper.orderByDesc("order_by");

        List<CouponPackage> list = couponPackageMapper.selectList(queryWrapper);
        // 卡包列表迭代器
        Iterator<CouponPackage> iterator = list.iterator();
        while (iterator.hasNext()) {
            CouponPackage next = iterator.next();
            String coupons = next.getCoupons();
            String[] split = coupons.split(",");
            for (String s : split) {
                Integer couponId = couponCodeService.getBaseMapper().countRemainByCouponId(s);
                // 券码数量为 0
                if (couponId == 0) {
                    // 清除卡包
                    iterator.remove();
                }
            }
        }
        return list;
    }

    /**
     * 检查卡包内的卡券是否还有剩余
     *
     * @param id 卡包 id
     * @return 有剩余返回 true
     */
    public Boolean checkRemainById(Integer id) {
        CouponPackage couponPackage = new CouponPackage().selectById(id);
        String[] split = couponPackage.getCoupons().split(",");
        for (String s : split) {
            Integer couponId = couponCodeService.getBaseMapper().countRemainByCouponId(s);
            // 券码数量为 0
            if (couponId == 0) {
                return false;
            }
        }
        return true;
    }
}
